<template>
  <pageTabelLayout>
    <template #pageHeader>
      <div class="my-tool-bar">
        <Toolbar
          :items="pageData.btnList"
          @add="addHandler"
          @del="deleteHandler"
          @select="selectHandler"
        >
        </Toolbar>
      </div>
    </template>
    <template #pageTabel>
      <AgGridVuesCopys
        :rowHeight="33"
        :headerHeight="33"
        rowSelection="multiple"
        @grid-ready="gridReady"
        style="height: calc(100% - 45px)"
        :defaultColDef="defaultColDef"
        class="ag-theme-alpine"
        :rowData="table.dataList"
        :columnDefs="tc"
        :localeText="localeText1"
      ></AgGridVuesCopys>
      <paginationCopys
      :total="total"
      show-total
      show-jumper
      show-page-size
      :page-size="pagination.pageSize"
      :current="pagination.page"
      @change="PageSize"
      @page-size-change="change1"
      style="justify-content: center"
    />
    </template>
    

    <a-drawer
      ok-text="保存"
      cancel-text="关闭"
      :drawer-style="{ zIndex: 9999 }"
      :mask-closable="false"
      :width="400"
      :ok-loading="pageData.pageLoading"
      :visible="pageData.showAdd"
      unmountOnClose
      @ok="sideOk"
      @cancel="pageData.showAdd = false"
    >
      <template #title>
        {{ pageData.sideTitle }}
      </template>
      <div>
        <a-form ref="formRef" layout="horizontal" :model="dataForm">
          <a-form-item
            label-col-flex="80px"
            label="机型"
            field="millType"
            :validate-trigger="['change', 'blur']"
            :rules="[{ required: true, message: '机型必填' }]"
          >
            <a-select popup-container="html" 
              class="bacClass"
              :allowClear="true"
              @search="handleSearch1"
              :loading="loading1"
              v-model="dataForm.millType"
              :filter-option="false"
              allow-search
              @focus="focusSel1"
            >
              <a-option v-for="item in pageData.nameList1" :value="item['detailName']">{{
                item['detailName']
              }}</a-option>
            </a-select>
          </a-form-item>
          <a-form-item
            label-col-flex="80px"
            label="是否开幅"
            field="openNot"
            :validate-trigger="['change', 'blur']"
            :rules="[{ required: true, message: '是否开幅必填' }]"
          >
            <a-select popup-container="html" 
              class="bacClass"
              v-model="dataForm.openNot"
              allow-search
              :allowClear="true"
              :filter-option="false"
            >
              <a-option :value="0">不开幅</a-option>
              <a-option :value="1">开幅</a-option>
              <!-- <a-option :value="2"> </a-option> -->
            </a-select>
          </a-form-item>
          <a-form-item
            label-col-flex="80px"
            label="单价"
            field="unitPrice"
            :validate-trigger="['change', 'blur']"
            :rules="[{ required: true, message: '单价必填' }]"
          >
            <a-input-number
              :precision="2"
              class="input-demo bacClass"
              v-model="dataForm.unitPrice"
            />
          </a-form-item>
          <a-form-item
            label-col-flex="80px"
            label="单位"
            field="unit"
            :validate-trigger="['change', 'blur']"
            :rules="[{ required: true, message: '单位必填' }]"
          >
            <a-select popup-container="html" 
              class="bacClass"
              :allowClear="true"
              @search="handleSearch3"
              v-model="dataForm.unit"
              :loading="loading3"
              :filter-option="false"
              allow-search
              @focus="focusSel3"
            >
              <a-option v-for="item in pageData.nameList3" :value="item['detailName']">{{
                item['detailName']
              }}</a-option>
            </a-select>
          </a-form-item>
          <a-form-item label-col-flex="80px" label="备注">
            <a-textarea
              class="bacClass"
              placeholder=""
              v-model="dataForm.remark"
              :max-length="400"
              allow-clear
              show-word-limit
            />
          </a-form-item>
        </a-form>
      </div>
    </a-drawer>
  </pageTabelLayout>
</template>

<script setup lang="ts">
  import { post } from '@/api/http'
  import {
    useTable,
    useRowKey,
    useTableColumn,
    usePagination,
    useRowSelection,
  } from '@/hooks/table'
  import emitter from '@/hooks/useEventBus'
  import { ref, reactive, onMounted, toRefs } from 'vue'
  import Toolbar from '@/components/Toolbar.vue'
  import { Form, Message, Modal } from '@arco-design/web-vue'
  import { FormInstance } from '@arco-design/web-vue/es/form'
  import { baseURL } from '../../../api/axios.config'
  import axios from 'axios'
  import filedownload from 'js-file-download'
  import usePermission from '@/store/modules/permission'
  import PageTabelLayout from '@/components/pageTabelLayout.vue'
  import { AnyARecord } from 'dns'
  
  import { localeText } from '@/api/aggridZw'
  interface BrandInfo {
    id: any
    remark: string | undefined
    createName: string | undefined
    createTime: string | undefined
    updateName: string | undefined
    updateTime: string | undefined
    deleteState: any
    millType: any
    openNot: any
    unitPrice: any
    unit: any
  }

  const total = ref(10)
  const page = ref(1)
  const size = ref(10)
  function PageSize(val: any) {
    pagination.page = val
    doRefresh()
  }

  function change1(val: any) {
    pagination.pageSize = val
    doRefresh()
  }
  const headerShow = ref<boolean>(true)
  //查询方法
  function doRefresh() {
    pageData.pageLoading = true
    post({
      url: 'pieceData/clothSet/getPage',
      data: {
        page: pagination.page,
        size: pagination.pageSize,
        deleteState: 0,
        // disassemblePrice: pageData.dropDownData
      },
    })
      .then(({ data, code }: any) => {
        if (code === 200) {
          table.handleSuccess(data.list)
          gridOption.value.setRowData(data.list)
          total.value = data.total
        }
      })
      .catch(console.log)
      .finally(() => {
        pageData.pageLoading = false
      })
  }

  const { selectedRowKeys, onSelectionChange } = useRowSelection()
  const pagination = usePagination(doRefresh)
  const table = useTable()
  const rowKey = useRowKey('id')
  const tableColumns = useTableColumn([
    {
      title: '机型',
      key: 'millType',
      dataIndex: 'millType',
      width: 150,
    },
    {
      title: '是否开幅',
      key: 'openNot',
      dataIndex: 'openNot',
      width: 150,
      slotName: 'actions',
    },
    {
      title: '单价',
      key: 'unitPrice',
      dataIndex: 'unitPrice',
      width: 150,
    },
    {
      title: '单位',
      key: 'unit',
      dataIndex: 'unit',
      width: 150,
    },
    {
      title: '备注',
      key: 'remark',
      dataIndex: 'remark',
      width: 200,
    },
    {
      title: '创建人',
      key: 'createName',
      dataIndex: 'createName',
      width: 150,
    },
    {
      title: '创建时间',
      key: 'createTime',
      dataIndex: 'createTime',
      width: 200,
    },
    {
      title: '最后修改人',
      key: 'updateName',
      dataIndex: 'updateName',
      width: 150,
    },
    {
      title: '最后修改时间',
      key: 'updateTime',
      dataIndex: 'updateTime',
      width: 200,
    },
    {
      title: '操作',
      key: 'id',
      slotName: 'act',
      width: 150,
      fixed: 'right',
    },
  ])
  let tc: any[] = tableColumns.map((o) => {
    let obj = {
      headerName: o.title,
      field: o.key,
      pinned: o['fixed'],
      tooltipField: o.key,
    }
    if (o.slotName === 'act') {
      obj['resizable'] = false
      obj['filter'] = false
      obj['sortable'] = false
      obj['lockPosition'] = 'right'
      obj['width'] = 80

      obj['cellRenderer'] = {
        // template: `<a-tag color="#ff7d00" @click="a" class="gesture">修改</a-tag>`,
        template: `<el-button style="color:#165dff;"  v-if="isEdit" type="info" link @click="a">修改</el-button>`,
        setup(props: any) {
          const a = () => {
            editHandler(props.params.data)
          }
          let isEdit = permissionStore.hasPermisson('csdj.xg')
          return {
            a,
            isEdit,
          }
        },
      }
    }
    if (o.slotName === 'actions') {
      obj['resizable'] = false
      obj['filter'] = true
      obj['sortable'] = false
      obj['cellRenderer'] = {
        template: `<a-space>
            <a-tag class="tagCss" style="color:#165dff !important" v-if="a.openNot ==0" >不开幅</a-tag>
            <a-tag v-if="a.openNot ==1" class="tagCss" style="color:#909399 !important">开幅</a-tag>
           </a-space>`,
        setup(props: any) {
          return {
            a: props.params.data,
          }
        },
      }
      obj['filterParams'] = {
        valueFormatter: function (params) {
          return params.value == '0' ? '不开幅' : params.value == '1' ? '开幅' : ''
        },
      }
    }

    return obj
  })

  let a = [
    {
      showRowGroup: 'hide_def',
      headerName: '',
      checkboxSelection: true,
      headerCheckboxSelection: true,
      pinned: 'left',
      width: 50,
      resizable: false,
      filter: false,
      sortable: false,
      minWidth: 50,
      maxWidth: 50,
      lockPosition: 'left',
    },
  ]
  tc = a.concat(tc)

  const pageData = reactive<{
    showAdd: boolean
    sideTitle: string
    dropDownData: any
    nameList: []
    pageLoading: boolean
    typeList: []
    dropDownData1: any
    rHeight: any
    btnList: any[]
    isEdit: boolean
    UnitList: any[]
    nameList3: any[]
    nameList1: any[]
  }>({
    nameList: [],
    showAdd: false,
    sideTitle: '新增验布机型单价',
    dropDownData: '',
    pageLoading: false,
    typeList: [],
    dropDownData1: '',
    rHeight: 2,
    btnList: [],
    isEdit: false,
    UnitList: [],
    nameList3: [],
    nameList1: [],
  })

  onMounted(() => {
    // 切换tap到本页面执行的方法
    emitter.on('FabricPrice1', () => {
      doRefresh()
    })
  })

  let cxbl = {}
  //查询
  const selectHandler = () => {
    pagination.page = 1
    cxbl = pageData.dropDownData
    doRefresh()
  }
  const queryData = reactive({
    disassemblePrice: '',
  })
  const addHandler = () => {
    for (var key in dataForm) {
      if (key === 'id') {
        dataForm[key] = null
      } else {
        dataForm[key] = ''
      }
    }
    pageData.showAdd = true
    pageData.sideTitle = '新增验布机型单价'
  }
  const dataForm = reactive<BrandInfo>({
    id: null,
    remark: '',
    createName: '',
    createTime: '',
    updateName: '',
    updateTime: '',
    deleteState: 0,

    millType: '',
    openNot: 0,
    unitPrice: null,
    unit: '',
  })

  // 表格准备事件
  const gridOption = ref()
  const gridReady = (params: any) => {
    gridOption.value = params.api
  }

  const formRef = ref<FormInstance>()
  const sideOk = () => {
    // if (dataForm.openNot === "" || dataForm.openNot === null || dataForm.openNot === undefined) {
    //     if (dataForm.openNot !== 0) {
    //         dataForm.openNot = 2
    //     }
    // }
    formRef.value?.validate().then((err) => {
      if (!err) {
        formRef.value?.validate().then((err) => {
          if (!err) {
            pageData.pageLoading = true
            if (pageData.sideTitle === '新增验布机型单价') {
              post({
                url: 'pieceData/clothSet/insert',
                data: [dataForm],
              })
                .then((res: any) => {
                  if (res.code === 200) {
                    formRef.value?.resetFields()
                    pageData.showAdd = false
                    Message.success({
                      content: '新增成功',
                      duration: 5000,
                    })
                  } else {
                    Message.error({
                      content: res.message,
                      duration: 5000,
                    })
                  }
                  doRefresh()
                })
                .finally(() => {
                  doRefresh()
                  pageData.pageLoading = false
                })
            } else {
              post({
                url: 'pieceData/clothSet/update',
                data: [dataForm],
              })
                .then((res: any) => {
                  if (res.code === 200) {
                    formRef.value?.resetFields()
                    pageData.showAdd = false
                    Message.success({
                      content: '修改成功',
                      duration: 5000,
                    })
                  } else {
                    Message.error({
                      content: res.message,
                      duration: 5000,
                    })
                  }
                  //doRefresh();
                })
                .finally(() => {
                  doRefresh()
                  pageData.pageLoading = false
                })
            }
          }
        })
      }
    })
  }
  const deleteHandler = () => {
    if (gridOption.value.getSelectedRows().length === 0) {
      Message.error('请先勾选')
      return
    }
    Modal.confirm({
      title: '系统提示',
      content: '确认删除选中的数据?',
      onOk() {
        pageData.pageLoading = true
        post({
          url: 'pieceData/clothSet/delete',
          data: gridOption.value.getSelectedRows().map((o: any) => {
            return o.id
          }),
        })
          .then(({ code, data }: any) => {
            if (code === 200) {
              Message.success({
                content: '删除成功',
                duration: 5000,
              })
              pagination.page = 1
              doRefresh()
            } else {
              Message.error({
                content: '删除失败',
                duration: 5000,
              })
            }
          })
          .finally(() => {
            pageData.pageLoading = false
          })
      },
    })
  }
  const editHandler = (record: BrandInfo) => {
    //循环对象 赋值
    for (let key in record) {
      dataForm[key] = record[key]
    }
    pageData.sideTitle = '修改验布机型单价'
    pageData.showAdd = true
  }
  //判断是否填写了中文
  const isChiese = (value: string, cb: Function) => {
    return new Promise<void>((resolve) => {
      if (window.encodeURI(value).indexOf('%') !== -1) {
        cb('填写的值只能是英文数字组合或英文，数字！')
      }
      resolve()
    })
  }
  //input离开焦点 将小写转大写
  const inputBlur = () => {
    dataForm.unit = dataForm.unit.toUpperCase()
  }

  const handleChange = (_data: any) => {
    table.handleSuccess(_data)
  }
  const defaultColDef = {
    sortable: true,
    resizable: true,
    filter: true,
    // flex: 1
  }
  const localeText1: any = ref(localeText)
  //  :items="['查询', '新增', '删除']"
  //设置权限
  const permissionStore = usePermission()
  if (permissionStore.hasPermisson('csdj.cx')) {
    pageData.btnList.push('查询')
  }
  if (permissionStore.hasPermisson('csdj.xz')) {
    pageData.btnList.push('新增')
  }
  if (permissionStore.hasPermisson('csdj.sc')) {
    pageData.btnList.push('删除')
  }

  const focusSel1 = () => {
    selCxAll1({ typeName: '' })
  }
  const options1 = ref<any>(pageData.nameList1)
  const loading1 = ref(false)
  const handleSearch1 = (value: any) => {
    if (value) {
      const ob = { typeName: value }
      loading1.value = true
      selCxAll1(ob)
      options1.value = pageData.nameList1
      loading1.value = false
    } else {
      options1.value = []
    }
  }
  function selCxAll1(val: any) {
    post({
      url: 'dict/dictTypeDetail/getList',
      data: {
        codeType: 46,
      },
    }).then(({ data, code }: any) => {
      if (code === 200) {
        pageData.nameList1 = data
      } else {
        Message.error({
          content: '查询失败！',
          duration: 5000,
        })
      }
    })
  }
  const focusSel3 = () => {
    selCxAll3({ codeType: '' })
  }
  const options3 = ref<any>(pageData.nameList3)
  const loading3 = ref(false)
  const handleSearch3 = (value: any) => {
    if (value) {
      const ob = { codeType: value }
      loading3.value = true
      selCxAll3(ob)
      options3.value = pageData.nameList3
      loading3.value = false
    } else {
      options3.value = []
    }
  }
  function selCxAll3(val: any) {
    post({
      url: 'dict/dictTypeDetail/getList',
      data: { codeType: 17 },
    }).then(({ data, code }: any) => {
      if (code === 200) {
        pageData.nameList3 = data
      } else {
        Message.error({
          content: '查询失败！',
          duration: 5000,
        })
      }
    })
  }

  // const change122 = (res: any) => {
  //     console.log(res, 'iiiiiiiiiiiiiiii');
  //     if (res == null) {
  //         dataForm.openNot = 2
  //     } else if (res == 0) {
  //         dataForm.openNot = 0
  //     } else {
  //         dataForm.openNot = 1
  //     }
  // }
</script>
<script lang="ts">
  export default {
    name: 'FabricPrice1',
  }
</script>
<style scoped lang="less">
  :deep(.ag-cell) {
    border-right: 1px solid #dde2eb;
  }

  :deep(.ag-header-cell) {
    border-right: 1px solid #dde2eb;
  }

  :deep(.ag-cell-value) {
    user-select: initial;
    -moz-user-select: text;
    -ms-user-select: text;
    -webkit-user-select: text;
  }
</style>
